import { Button, Modal, Radio, Space, Table } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import Draw from 'ol/interaction/Draw';
import useBusinessMap from '../BusinessMap/useBusinessMap';
import { createLayer, geoJsonToFeature, geomToGeoJson } from '../../../utils/helper/mapHelper';
import {
    LineString,
    MultiLineString,
    MultiPoint,
    MultiPolygon,
    Point,
    Polygon,
} from 'ol/geom';
import { Fill, Stroke, Style } from 'ol/style';

const turf = window.turf
export default function DrawComponent(props) {
    const [type, setType] = useState();
    const map = useBusinessMap();
    const drawRef = useRef();
    const [geom, setGeom] = useState();


    const drawLayer = useMemo(() => {
        if (map) {
            const layer = createLayer();
            map.addLayer(layer)
            return layer
        }
    }, [map])

    useEffect(() => {
        return () => {
            drawLayer.getSource().clear();
            map.removeInteraction(drawRef.current);
        }
    }, [drawLayer, map])
    function addInteraction(type) {
        if (drawLayer) {
            const draw = drawRef.current = new Draw({
                source: drawLayer.getSource(),
                type: type,
                stopClick: true,
                geometryFunction: (coordinates, geometry) => {
                    switch (type) {
                        case 'Point':
                            geometry = new Point(coordinates);
                            break;
                        case 'LineString':
                            if (geometry) {
                                geometry.setCoordinates(coordinates);
                            } else {
                                geometry = new LineString(coordinates);
                            }
                            break;
                        case 'Polygon':
                            if (geometry) {
                                if (coordinates[0].length) {
                                    // Add a closing coordinate to match the first
                                    geometry.setCoordinates([coordinates[0].concat([coordinates[0][0]])]);
                                } else {
                                    geometry.setCoordinates([]);
                                }
                            } else {
                                geometry = new Polygon(coordinates);
                            }
                            break;
                        default:
                    }
                    if (geometry) {
                        if (type === 'Polygon' && geometry.getCoordinates()?.[0].length < 4) {
                            return geometry;
                        }
                        const geojson = geomToGeoJson(geometry);
                        const newGeojson = turf.buffer(geojson, props.radius, {
                            units: 'meters'
                        });

                        const newFeature = geoJsonToFeature(newGeojson);
                        newFeature.setStyle(new Style({
                            fill: new Fill({
                                color: 'rgba(0,255,255,0.3)'
                            }),
                            stroke: new Stroke({
                                color: 'rgba(0,255,255,1)',
                                width: 1,
                                lineDash: [10, 10]
                            })
                        }))
                        newFeature.set('type', 'bufferFeature')
                        const source = drawLayer.getSource()
                        const lastFeature = source.getFeatures().find(f => f.get('type') === 'bufferFeature');
                        source.removeFeature(lastFeature)
                        source.addFeature(newFeature)

                    }
                    return geometry;
                }
            });
            draw.on('drawend', (evt) => {
                // console.log(evt)
                const geom = evt.feature.getGeometry();

                const geojson = geomToGeoJson(geom);
                const newGeojson = turf.buffer(geojson, props.radius, {
                    units: 'meters'
                });

                const newFeature = geoJsonToFeature(newGeojson);
                setGeom(newFeature.getGeometry())
                props.onDrawEnd?.(newFeature.getGeometry())
                // const wkt = geomToWkt(geom);
                // Modal.info({
                //     title: "wkt字符串",
                //     content: <Input.TextArea rows={10} value={wkt} />
                // })
                setType(null);
                map.removeInteraction(draw);
            })
            map.addInteraction(draw);
        }
    }

    return <div className='layout-v'>
        <div className='layout-h center'>
            <Radio.Group className='fill' buttonStyle='solid' size='small' value={type} onChange={e => {
                setType(e.target.value)
                drawLayer.getSource().clear();
                map.removeInteraction(drawRef.current);
                addInteraction(e.target.value);
            }}>
                <Radio.Button value={"Point"}>点</Radio.Button>
                <Radio.Button value={"LineString"}>线</Radio.Button>
                <Radio.Button value={"Polygon"}>面</Radio.Button>
            </Radio.Group>
            <Space>
                <Button size="small" onClick={e => {
                    drawLayer.getSource().clear();
                    setType(null)
                    map.removeInteraction(drawRef.current);
                    setGeom(null)

                    props.onDrawEnd?.(null)
                }}>清除</Button>
            </Space>
        </div>
        <div style={{
            marginTop: 8
        }}>
            绘制状态：{geom ? <span style={{
                color: '#87d068'
            }}>已完成绘制</span> : <span style={{
                color: '#f50',
                fontStyle: 'italic'
            }}>未完成绘制</span>}

        </div>
    </div>
}